#import "USToolBar.h"

@interface USToolBar ()
@property (nonatomic, strong) UIStackView *stackView;
@property (nonatomic, strong) NSLayoutConstraint *heightConstraint;
@end

@implementation USToolBar

- (instancetype)initWithButtons:(NSArray<UIButton *> *)buttons layoutType:(USToolBarLayoutType)layoutType {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        [self setupWithButtons:buttons layoutType:layoutType];
    }
    return self;
}

- (void)setupWithButtons:(NSArray<UIButton *> *)buttons layoutType:(USToolBarLayoutType)layoutType {
    self.backgroundColor = UIColor.mi_1_color;

    // contentView
    _contentView = [[UIView alloc] init];
    [self addSubview:_contentView];

    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.height.mas_equalTo(44);
    }];

    // stackView
    _stackView = [[UIStackView alloc] initWithArrangedSubviews:buttons];
    _stackView.axis = UILayoutConstraintAxisHorizontal;
    _stackView.spacing = 20;
    _stackView.alignment = UIStackViewAlignmentCenter;
    _stackView.translatesAutoresizingMaskIntoConstraints = NO;

    [_contentView addSubview:_stackView];

    // 配置分布方式
    switch (layoutType) {
        case USToolBarLayoutTypeLeft:
            _stackView.distribution = UIStackViewDistributionEqualSpacing;
            [_stackView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(20);
                make.centerY.mas_equalTo(0);
            }];
            break;

        case USToolBarLayoutTypeRight:
            _stackView.distribution = UIStackViewDistributionEqualSpacing;
            [_stackView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_offset(-20);
                make.centerY.mas_equalTo(0);
            }];
            break;

        case USToolBarLayoutTypeCenter:
            _stackView.spacing = 0;
            _stackView.distribution = UIStackViewDistributionEqualSpacing;
            [_stackView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(20);
                make.right.mas_offset(-20);
                make.top.bottom.mas_offset(0);
            }];
            break;
    }

    // 设置整体高度（根据 safeArea）
    self.heightConstraint = [self.heightAnchor constraintEqualToConstant:44];
    self.heightConstraint.active = YES;
    
}


- (void)updateHeightIfNeeded {
    CGFloat safeBottom = self.superview.safeAreaInsets.bottom;
    CGFloat newHeight = 44 + (safeBottom > 0 ? safeBottom + 2 : 0);
    self.heightConstraint.constant = newHeight;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self updateHeightIfNeeded];
    
}

@end
